package com.lmm.lcbusiness.lcbusiness.pages.choosecity;

import com.blankj.utilcode.util.PinyinUtils;
import com.lmm.dresswisdom.lmmframe.retrofit.AppCallBack;
import com.lmm.dresswisdom.lmmframe.retrofit.AppClient;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;
import com.lmm.lcbusiness.lcbusiness.BaseReturnInfo;
import com.lmm.lcbusiness.lcbusiness.config.ConfigValue;
import com.lmm.lcbusiness.lcbusiness.config.DataSafeUtil;
import com.lmm.lcbusiness.lcbusiness.dbmodel.AreaRealm;
import com.lmm.lcbusiness.lcbusiness.utils.RealmUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * @author xmgong
 */
public class ChooseCityPresent implements ChooseCityContract.IPresent {

    ChooseCityContract.IView mView;
    ChooseCityAction mAction = null;

    public ChooseCityPresent(ChooseCityContract.IView mView) {
        this.mView = mView;
        mAction = AppClient.getRetrofit(ConfigValue.apiUrl).create(ChooseCityAction.class);
    }

    @Override
    public void updateCityAction() {
        Map<String, String> params = new HashMap<>();
        AppClient.request(mAction.getAllCitys(DataSafeUtil.EncodeMAP(params)), new AppCallBack<BaseReturnInfo<List<AreaDataModel>>>() {
            @Override
            public void onSuccess(BaseReturnInfo<List<AreaDataModel>> model) {
                if (model.isSuccess()) {
                    List<AreaDataModel> areaModelList = model.getData();
                    AreaRealm am = null;
                    List<AreaRealm> amLst = new ArrayList<>();
                    for (AreaDataModel a : areaModelList) {
                        am = getAM(a);
                        amLst.add(am);
                    }
                    saveCity(amLst);
                } else {
                    ToastUtils.showToastShort(model.getMessage());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtils.showToastShort(msg);
            }

            @Override
            public void onFinish() {
                mView.updateCitysFinish();
            }
        });
    }

    @Override
    public void getAllCitys() {
        Realm realm = RealmUtils.getRealm();
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                RealmResults<AreaRealm> res = realm.where(AreaRealm.class).in("type", new Integer[]{1, 2}).findAll();
                if (res != null && res.size() > 0) {
                    List<AreaInfoModel> data = new ArrayList<>();
                    AreaInfoModel aim = null;
                    for (AreaRealm am : res) {
                        aim = new AreaInfoModel();
                        aim.setName(am.getName());
                        aim.setCityCode(am.getCode());
                        aim.setTitle(am.getName());
                        data.add(aim);
                    }
                    sortCtiys(data);
                }
            }
        });
    }

    @Override
    public void sortCtiys(List<AreaInfoModel> res) {
        //排序
        // 根据a-z进行排序源数据
        Collections.sort(res, new Comparator<AreaInfoModel>() {
            @Override
            public int compare(AreaInfoModel o1, AreaInfoModel o2) {
                //这里主要是用来对ListView里面的数据根据ABCDEFG...来排序
                if (getPinYin(o2.getName()).equals("#")) {
                    return -1;
                } else if (getPinYin(o1.getName()).equals("#")) {
                    return 1;
                } else {
                    return getPinYin(o1.getName()).compareTo(getPinYin(o2.getName()));
                }
            }
        });

        mView.getCityReturn(res);
    }

    @Override
    public void searchCity(String s) {
        Realm realm = RealmUtils.getRealm();
        realm.beginTransaction();
        RealmResults<AreaRealm> res = realm.where(AreaRealm.class).like("name", "*" + s + "*").findAll();
        realm.commitTransaction();
        if (res != null && res.size() > 0) {
            List<AreaInfoModel> data = new ArrayList<>();
            AreaInfoModel aim = null;
            for (AreaRealm am : res) {
                if (am.getType() != 0) {
                    aim = new AreaInfoModel();
                    aim.setName(am.getName());
                    aim.setCityCode(am.getCode());
                    //根据parentid获取父类名称
                    AreaRealm parent = getCityById(am.getParentId());
                    if (parent != null) {
                        aim.setTitle(am.getName() + "," + parent.getName());
                    } else {
                        aim.setTitle(am.getName());
                    }
                    data.add(aim);
                }
            }
            sortCtiys(data);
        }
    }

    @Override
    public int getDBCity() {
        Realm realm = RealmUtils.getRealm();
        return (int) realm.where(AreaRealm.class).count();
    }

    @Override
    public Map<String, String> getShenShiQu(String code) {
        String shencode = "";
        String shicode = "";
        String qucode = "";
        Map<String, String> map = new HashMap<>();
        if (code.length() > 0) {

            if (code.length() >= 3) {
                shencode = code.substring(0, 3);
            }
            if (code.length() >= 6) {
                shicode = code.substring(0, 6);
            }
            if (code.length() == 9) {
                qucode = code;
            }
            Realm realm = RealmUtils.getRealm();
            if (shencode.length() > 0) {
                String shen = realm.where(AreaRealm.class).equalTo("code", shencode).findFirst().getName();
                map.put("shen", shen);
            }
            if (shicode.length() > 0) {
                String shi = realm.where(AreaRealm.class).equalTo("code", shicode).findFirst().getName();
                map.put("shi", shi);
            }
            if (qucode.length() > 0) {
                String qu = realm.where(AreaRealm.class).equalTo("code", qucode).findFirst().getName();
                map.put("xian", qu);
            }
        }
        return map;
    }

    public String getPinYin(String name) {
        String py = "";
        if (!name.equals("")) {
            py = PinyinUtils.ccs2Pinyin(name).substring(0, 1).toLowerCase();
        }
        return py;
    }

    public AreaRealm getAM(AreaDataModel adm) {
        AreaRealm areaRealm = new AreaRealm();
        areaRealm.setCategory(adm.category);
        areaRealm.setCode(adm.code);
        areaRealm.setId(adm.id);
        areaRealm.setLevel(adm.level);
        areaRealm.setName(adm.name);
        areaRealm.setParentId(adm.parentId);
        areaRealm.setType(adm.type);
        areaRealm.setSortNo(adm.sortNo);
        return areaRealm;
    }

    private AreaRealm getCityById(int id) {
        AreaRealm am;
        Realm realm = RealmUtils.getRealm();
        realm.beginTransaction();
        am = realm.where(AreaRealm.class).equalTo("id", id).findFirst();
        realm.commitTransaction();
        return am;
    }

    private void saveCity(List<AreaRealm> res) {
        Realm realm = RealmUtils.getRealm();
        realm.beginTransaction();
        realm.delete(AreaRealm.class);
        for (AreaRealm item : res) {
            realm.copyToRealm(item);
        }
        realm.commitTransaction();
    }


}